
package com.hs.common;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.quartz.SchedulerException;

import com.hs.Environment;
import com.hs.core.db.DatabaseConnection;
import com.hs.core.setup.SetupDatabase;
import com.hs.db.DatabaseUtil;
import com.hs.db.NetworkServerUtil;
import com.hs.job.core.ScheduleManager;
import com.hs.utils.Utilities;
import com.hs.utils.XMLUtil;

public class AppInit extends HttpServlet
{
	NetworkServerUtil netWork = null;
	ScheduleManager instSm = null;
    public AppInit()
    {
		netWork = NetworkServerUtil.getInstance(Environment.getValue(Environment.PROP_BASE_DATABASE_IP), Environment.getIntValue(Environment.PROP_BASE_DATABASE_PORT), new PrintWriter(System.out));
		instSm = ScheduleManager.getInstance();
//		
    }

    public void init(ServletConfig config)
        throws ServletException
    {
        super.init(config);  
        loadAnsiSql(getInitParameter("hs.sql.ansi").replace('%', '$'));
        netWork.start();
        
        try {
			netWork.testForConnection();
			//netWork.trace(true);
		} catch (Exception e) { 
			System.out.println("Derby Network Server is run with problem ! ");
			netWork.shutdown();
			netWork.start();
			e.printStackTrace();
		}
		Connection con = null;
		boolean isInit = Environment.getBooleanValue(Environment.PROP_IS_INIT);
		try {
			con = DatabaseConnection.getConnection();
		} catch (Exception e) {
			if(isInit){
				System.out.println("数据库不存在重新创建");
				DatabaseUtil util = new DatabaseUtil();
				util.createDatabase(Environment.getValue(Environment.PROP_DB_URL)+"user="+Environment.getValue(Environment.PROP_DB_USERNAME)+";password="+Environment.getValue(Environment.PROP_DB_PASSWORD),isInit);
				System.out.println("________________________数据库初始化______________________________");
				SetupDatabase setup = new SetupDatabase(); 
				try {
					con = DatabaseConnection.getConnection();
					setup.createTables(con);
				} catch (Exception e1) { 
					e1.printStackTrace();
				}
				System.out.println("________________________数据库初始化完成______________________________");
				
			  }  
		}finally{
			if(null != con){
				try {
					con.close();
				} catch (SQLException e1) { 
					e1.printStackTrace();
				}
			}
		}
//		
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
    	loadAnsiSql(null);
    }

    public void loadAnsiSql(String filePath)
        throws ServletException
    {
        if(filePath == null)
        	filePath = System.getProperty("hs.sql.ansi");
        if(filePath == null)
            throw new ServletException("Can't find hs conf root param!");
        System.out.println("Hs Framework 1.0.0 Starting...");
        try
        {
            String appPath = getServletContext().getRealPath("/");
            String classLoderPath = Utilities.getClassLoaderRoot().getAbsolutePath();
            String fullPath = classLoderPath + System.getProperty("file.separator") + filePath;
            int sqlSize = XMLUtil.parseXML2Map(fullPath);
            System.out.println("共加载SQL：" + sqlSize + "条!");
            System.out.println("dbpath:" + Utilities.getDbRoot().getParent());
            String dbpath = Utilities.getDbRoot().getParent() + System.getProperty("file.separator")+"derby";
            System.setProperty("derby.system.home",dbpath);
//            if(null != instSm)
//    			try {
//    				instSm.run();
//    			} catch (SchedulerException e) {
//    				System.out.println("任务调度服务启动异常：" + e.getMessage());
//    			}
        }
        catch(Exception e)
        {
            e.printStackTrace();
            System.out.println("Hs Framework 1.0.0 initial fail.");
            return;
        }
        System.out.println("Hs Framework 1.0.0 Start OK.");
    }
    public void destroy(){
    	if(null != netWork)
    		netWork.shutdown(); 
    	try {
			if(null != instSm)
				instSm.shutdown();
		} catch (SchedulerException e) {
			System.out.println("任务调度服务停止异常:" + e.getMessage());
		}
    	System.out.println("应用服务停止，服务脏听");
    }

}
